package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserItemVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.security.MessageDigest;

/**
 * @author liubo
 * @description 针对表【system_user(员工信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser>
        implements SystemUserService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public void customPage(Page<SystemUserItemVo> page, SystemUserQueryVo queryVo) {
        page = systemUserMapper.customQueryPage(page,queryVo);
    }

    @Override
    public SystemUserItemVo customById(Long id) {
        SystemUserItemVo systemUserItemVo = systemUserMapper.customById(id);
        return systemUserItemVo;
    }

    @Override
    public void customSaveOrUpdate(SystemUser systemUser) {

        //1.检查账号问题（不能重复 保存-》都不能重复 更新-》可以跟原有的重复，不能跟别的重复）
//        SELECT COUNT(*) FROM SYSTEM_USER WHERE username = "xxxx"
//        SELECT COUNT(*) FROM SYSTEM_USER WHERE username = "xxxx" AND id != 1;
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,systemUser.getUsername());
        lambdaQueryWrapper.ne(systemUser.getId() != null, SystemUser::getId,systemUser.getId());
        long count = count(lambdaQueryWrapper);

        if (count > 0){
            throw  new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_EXIST_ERROR);
        }
        //2. 密码加密 （更新还是保存）
        if (!ObjectUtils.isEmpty(systemUser.getPassword())){
            //md5
            systemUser.setPassword(DigestUtils.md5Hex(systemUser.getPassword()));
        }
        //3. 调用更新和保存方法
        saveOrUpdate(systemUser);

    }
}




